# app/core/config.py (Pydantic V2 完整修复版)
from pydantic_settings import BaseSettings, SettingsConfigDict  # 从 pydantic-settings 导入
from pydantic import Field, field_validator
from typing import Optional
from pathlib import Path
import yaml
import os

# --------------------- 嵌套配置模型 ---------------------
class ServerSettings(BaseSettings):
    host: str = Field("localhost", description="服务器主机")
    port: int = Field(8000, description="服务器端口")

    model_config = SettingsConfigDict(frozen=True)  # V2 配置语法

class DatabaseSettings(BaseSettings):
    type: str = Field("mongodb", description="数据库类型")
    host: str = Field("localhost", description="数据库主机")
    port: int = Field(27017, description="数据库端口")
    username: str = Field(..., description="数据库用户名")
    password: str = Field(..., description="数据库密码")
    database: str = Field(..., description="数据库名称")

    @field_validator("port")
    def validate_port(cls, v: int) -> int:
        if not (1024 <= v <= 65535):
            raise ValueError("端口号必须在1024-65535之间")
        return v
    
class PredmodelSettings(BaseSettings):
    base_model_dir: str = Field("data_processor/base_model", description="预处理模型位置")
    pred_model_dir: str = Field("data_processor/pred_model", description="预测模型位置")
    

# --------------------- 全局配置模型 ---------------------
class Settings(BaseSettings):
    server: ServerSettings = ServerSettings()
    database: DatabaseSettings 
    predmodel: PredmodelSettings 

    model_config = SettingsConfigDict(
        env_prefix="APP_",
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore"
    )

    @classmethod
    def load_from_yaml(cls, config_path: Path) -> "Settings":
        """从YAML文件加载配置"""
        if not config_path.exists():
            return cls()
        
        try:
            with open(config_path, "r", encoding="utf-8") as f:
                yaml_data = yaml.safe_load(f)
            
            server_data = yaml_data.get("server", {})
            db_data = yaml_data.get("database", {})
            predmodel_data = yaml_data.get("predmodel", {})

            return cls(
                server=ServerSettings(**server_data),
                database=DatabaseSettings(**db_data),
                predmodel=PredmodelSettings(**predmodel_data)
            )
        except Exception as e:
            print(f"警告：配置文件加载失败 ({config_path}): {e}")
            return cls()

# --------------------- 配置加载入口 ---------------------
BASE_DIR = Path(__file__).parent.parent.resolve()
CONFIG_PATH = BASE_DIR / "config.yaml"

print(f"尝试加载配置文件: {CONFIG_PATH}")
print(f"文件是否存在: {CONFIG_PATH.exists()}")
print(f"当前工作目录: {os.getcwd()}")

try:
    config = Settings.load_from_yaml(CONFIG_PATH)
    print("配置加载成功!")
except Exception as e:
    print(f"警告：使用默认配置，原因：{e}")
    config = Settings()